<template>
  <div class="container">
    <!-- 优惠券列表 -->
    <van-popup
      v-model="showExchange"
      round
      position="bottom"
      style="height: 90%; padding-top: 4px; z-index: 2008"
    >
      <van-coupon-list
        v-model="cardNumber"
        :coupons="coupons"
        :chosen-coupon="chosenCoupon"
        :disabled-coupons="disabledCoupons"
        input-placeholder="请输入提货码"
        @exchange="onExchange"
        @change="change"
      />
    </van-popup>
  </div>
</template>

<script>
import { Popup, CouponList, Toast } from "vant";
import { getCouponsUser, getCouponByCard } from "@/api/user";
Toast.setDefaultOptions({
  className: "topest"
});
export default {
  name: "ExchangeCard",
  props: {
    showExchange: {
      type: Boolean,
      require: true
    }
  },
  data() {
    return {
      cardNumber: "",
      coupons: [],
      chosenCoupon: -1,
      disabledCoupons: []
    };
  },
  methods: {
    onExchange() {
      // 兑换提货码
      getCouponByCard(this.cardNumber)
        .then(res => {
          // 刷新优惠券列表
          Toast.success(res.msg);
          this.getCoupons();
        })
        .catch(err => Toast.fail(err.msg));
    },
    getCoupons() {
      getCouponsUser(1).then(res => {
        // 获取可用的优惠券
        this.coupons = this.formateCouponData(res.data);
      });
      getCouponsUser(2).then(res => {
        // 获取过期的优惠券
        this.disabledCoupons = this.formateCouponData(res.data);
      });
    },
    formateCouponData(coupons) {
      return coupons.map(coupon => {
        coupon.id = coupon.id.toString();
        coupon.name = coupon.coupon_title;
        coupon.condition = "满" + coupon.use_min_price + "元可用";
        coupon.startAt = new Date(coupon.add_time).valueOf() / 1000;
        coupon.endAt = new Date(coupon.end_time).valueOf() / 1000;
        coupon.reason = coupon._msg;
        coupon.value = Number(coupon.coupon_price) * 100;
        coupon.unitDesc = "元";
        return coupon;
      });
    },
    change: function(couponId) {
      this.showExchange = false;
      this.$emit("getCouponId", couponId);
    }
  },
  created() {
    this.getCoupons();
  },
  components: {
    [Popup.name]: Popup,
    [CouponList.name]: CouponList
  }
};
</script>

<style>
.topest {
  z-index: 5000;
}
</style>
